<script setup lang="tsx">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useRouter, useRoute } from 'vue-router'
import { merchantRelationBusinessListApi } from '@/api/BusinessManagement'
import { ElButton } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'

const { t } = useI18n()
const { go } = useRouter()
const { query } = useRoute()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await merchantRelationBusinessListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      id: unref(query.id as any),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '序号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'businessShortName',
    label: '商家简称',
    form: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: '关联时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  console.log(params)
  const { createTime, ...rest } = params
  let startCreateTime, endCreateTime
  if (createTime && createTime.length > 0) {
    startCreateTime = createTime[0]
    endCreateTime = createTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    startCreateTime,
    endCreateTime,
    ...rest
  }
  getList()
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentDetailWrap class="flex-[3] ml-20px" title="关联商家列表">
      <template #header>
        <ElButton @click="go(-1)">
          {{ t('common.back') }}
        </ElButton>
      </template>
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentDetailWrap>
  </div>
</template>
